package com.mstore.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class SendSms {
	
	private String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";
	
	private String account = "cf_judyhe";
	private String password = "84251121";
	
	public Map<String, Object> sendSMS(String mobile) {
		HttpClient client = new HttpClient(); 
		PostMethod method = new PostMethod(Url); 
			
		client.getParams().setContentCharset("UTF-8");
		method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=UTF-8");

		int mobile_code = (int)((Math.random()*9+1)*100000);

	    String content = new String("您的验证码是：" + mobile_code + "。请不要把验证码泄露给其他人。（无觅会员系统-MICRM）"); 

	    //提交短信
		NameValuePair[] data = {
			    new NameValuePair("account", account), 
			    new NameValuePair("password", StringUtil.MD5Encode(password)), //密码可以使用明文密码或使用32位MD5加密
			    new NameValuePair("mobile", mobile), 
			    new NameValuePair("content", content),
		};
		
		method.setRequestBody(data);		
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		try {
			client.executeMethod(method);	
			
			String SubmitResult =method.getResponseBodyAsString();
					
			Document doc = DocumentHelper.parseText(SubmitResult); 
			Element root = doc.getRootElement();


			String code = root.elementText("code");	
			String msg = root.elementText("msg");	
			String smsid = root.elementText("smsid");	
			
			map.clear();
			map.put("code", code);
			map.put("msg", msg);
			map.put("smsid", smsid);
			map.put("mobile_code", mobile_code);
			map.put("mobile", mobile);
			map.put("content", content);
			
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		}	
		return map;
	}
}
